<?php

// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------


namespace app\controller\admin\system\merchant;

use app\common\repositories\store\ExcelRepository;
use app\common\repositories\store\StoreCategoryRepository;
use app\common\repositories\system\CacheRepository;
use app\common\repositories\system\merchant\MerchantAdminRepository;
use app\common\repositories\system\merchant\MerchantRepository;
use app\common\repositories\system\merchant\MerchantTypeRepository;
use app\Request;
use app\validate\api\MerchantIntentionValidate;
use crmeb\listens\SwooleTaskListen;
use crmeb\services\ExcelService;
use crmeb\services\SwooleTaskService;
use EasyWeChat\ShakeAround\Relation;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Swoole\Http\Response;
use Swoole\Server;
use think\App;
use crmeb\basic\BaseController;
use app\common\repositories\system\merchant\MerchantIntentionRepository;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer;
use think\exception\ValidateException;
use think\route\dispatch\Controller;

class MerchantIntention extends BaseController
{
    protected $repository;

    /**
     * MerchantIntention constructor.
     * @param App $app
     * @param MerchantIntentionRepository $repository
     */
    public function __construct(App $app, MerchantIntentionRepository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
    }

    public function lst()
    {
        [$page, $limit] = $this->getPage();
        $where = $this->request->params(['mer_name', 'status', 'date', 'keyword', 'mer_intention_id', 'category_id', 'type_id']);
        return app('json')->success($this->repository->getList($where, $page, $limit));
    }

    public function form($id)
    {
        if (!$this->repository->getWhereCount(['mer_intention_id' => $id, 'is_del' => 0]))
            return app('json')->fail('数据不存在');
        return app('json')->success(formToData($this->repository->markForm($id)));
    }

    public function statusForm($id)
    {
        if (!$this->repository->getWhereCount(['mer_intention_id' => $id, 'is_del' => 0]))
            return app('json')->fail('数据不存在');
        return app('json')->success(formToData($this->repository->statusForm($id)));
    }

    public function mark($id)
    {
        if (!$this->repository->getWhereCount(['mer_intention_id' => $id, 'is_del' => 0]))
            return app('json')->fail('数据不存在');
        $data = $this->request->param('mark');
        $this->repository->update($id, ['mark' => $data]);
        return app('json')->success('修改成功');
    }

    public function switchStatus($id)
    {
        if (!$this->repository->getWhereCount(['mer_intention_id' => $id, 'is_del' => 0]))
            return app('json')->fail('数据不存在');
        $data = $this->request->params(['status', 'fail_msg', 'create_mer']);
        $data['status'] = $data['status'] == 1 ? 1 : 2;
        $this->repository->updateStatus($id, $data);
        return app('json')->success('修改成功');
    }

    public function create()
    {
        $data = $this->checkParams();
        $make = app()->make(MerchantRepository::class);
        if ($make->fieldExists('mer_name', $data['mer_name']))
            throw new ValidateException('商户名称已存在，不可申请');
        if ($make->fieldExists('mer_phone', $data['phone']))
            throw new ValidateException('手机号已存在，不可申请');
        $adminRepository = app()->make(MerchantAdminRepository::class);
        if ($adminRepository->fieldExists('account', $data['phone']))
            throw new ValidateException('手机号已是管理员，不可申请');
        $this->repository->create($data);
        return app('json')->success('提交成功');
    }

    protected function checkParams()
    {
        $data = $this->request->params(['phone', 'mer_name', 'name', 'code', 'images', 'merchant_category_id', 'mer_type_id'
            ,'legal_person_name'
            ,'legal_person_phone'
            ,'legal_person_card'
            ,'card_front'
            ,'card_opposite'
            ,'merchant_nature'
            ,'bank_name'
            ,'bank_card'
            ,'bank_bank'
            ,'bank_institution'
            ,'door_img'
            ,'cashier_img'
            ,'in_store_img'
            ,'uid'
        ]);
        app()->make(MerchantIntentionValidate::class)->check($data);
        $data['mer_type_id'] = (int)$data['mer_type_id'];
        if (!app()->make(StoreCategoryRepository::class)->get($data['merchant_category_id'])) throw new ValidateException('商户分类不存在');
        if ($data['mer_type_id'] && !app()->make(MerchantTypeRepository::class)->exists($data['mer_type_id']))
            throw new ValidateException('店铺类型不存在');
        unset($data['code']);
        return $data;
    }

    public function update($id)
    {
        if (!$this->repository->getWhere(['mer_intention_id' => (int)$id, 'is_del' => 0]))
            return app('json')->fail('数据不存在');
        $data = $this->checkParams();
        $data['create_time'] = date('Y-m-d H:i:s', time());
        $this->repository->updateIntention((int)$id, $data);
        return app('json')->success('修改成功');
    }

    public function delete($id)
    {
        if (!$this->repository->getWhereCount(['mer_intention_id' => $id, 'is_del' => 0]))
            return app('json')->fail('数据不存在');
        $this->repository->update($id, ['is_del' => 1]);
        return app('json')->success('删除成功');
    }

    /**
     * @Author:Qinii
     * @Date: 2020/9/15
     * @return mixed
     */
    public function saveAgree()
    {
        $agree = $this->request->param('agree');
        app()->make(CacheRepository::class)->save('sys_intention_agree', $agree);
        return app('json')->success('保存成功');
    }

    /**
     * @Author:Qinii
     * @Date: 2020/9/15
     * @return mixed
     */
    public function getAgree()
    {
        $make = app()->make(CacheRepository::class);
        return app('json')->success(['sys_intention_agree' => $make->getResult('sys_intention_agree')]);
    }

    public function excel()
    {
        $where = $this->request->params(['mer_name', 'status', 'date', 'keyword', 'mer_intention_id', 'category_id', 'type_id']);

        [$page, $limit] = $this->getPage();
        $data = app()->make(ExcelService::class)->intention($where,$page,$limit);
        return app('json')->success($data);


    }

    public function excel2()
    {
        // 设置表格的表头数据
        $header = ["A1" => "编号", "B1" => "姓名", "C1" => "年龄"];
        // 假设下面这个数组从数据库查询出的二维数组
        $data = [
            [1,'李朋',18],
            [2,'常师太',19],
            [3,'宋一个',22],
            [4,'朱贝贝',19],
            [5,'胡燕东',29]
        ];
        // 保存文件的类型
        $type= true;
        // 设置下载文件保存的名称
        $fileName = '1909A班违纪信息导出'.time();


        // 调用方法导出excel
//        self::export($header,$type,$data,$fileName);
//        $where = $this->request->params(['mer_name', 'status', 'date', 'keyword', 'mer_intention_id', 'category_id', 'type_id']);
//        [$page, $limit] = $this->getPage();
//        $data = app()->make(ExcelService::class)->intention($where,$page,$limit);
//        return app('json')->success($data);

        // 实例化类
        $preadsheet = new Spreadsheet();
        // 创建sheet
        $sheet = $preadsheet->getActiveSheet();
        // 循环设置表头数据
        foreach ($header as $k => $v) {
            $sheet->setCellValue($k, $v);
        }
        // 生成数据
        $sheet->fromArray($data, null, "A2");
        // 样式设置
        $sheet->getDefaultColumnDimension()->setWidth(12);
        // 设置下载与后缀

        $type = "Xls";

        // 调用方法执行下载
        $writer = IOFactory::createWriter($preadsheet, $type);
//        // 数据流
//        $writer->save("php://output");
        //设置filename
        $filename = '成绩名单-'.date('Ymd').'.xls';
        //保存
        $writer->save($filename);

//        $response= new Request();
//        $response->content(file_get_contents($filename));
//        $response->header(['Content-type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']);
//        $response->header(['Content-Disposition'=>'attachment;filename='.$filename]);
//        $response->header(['Cache-Control'=>'max-age=0']);
//        $response->send();

        var_dump((new Response())->write(file_get_contents($filename)));

//        (new \Swoole\Http\Response())->write(file_get_contents($filename));
//        (new \Swoole\Http\Response())->header('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//        (new \Swoole\Http\Response())->header('Content-Disposition', 'attachment;filename='.$filename);
//        (new \Swoole\Http\Response())->header('Cache-Control','max-age=0');
//        (new \Swoole\Http\Response())->end(file_get_contents($filename));
//        var_dump(122);
        //swoole下载文件，使用response输出
//            $this->response()->write(file_get_contents($filename));
//            $this->response()->withHeader('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//            $this->response()->withHeader('Content-Disposition', 'attachment;filename='.$filename);
//            $this->response()->withHeader(c);
//            $this->response()->end();
        return app('json')->success('保存成功');

    }


    /**
     * @param $id
     * @return mixed
     * User: fupeng
     * Date: 2023/10/11
     */
    public function detail($id)
    {
        $data = $this->repository->detail((int)$id,null,['merchantCategory','merchantType',]);
        if (!$data) {
            return app('json')->fail('数据不存在');
        }
        return app('json')->success($data);

    }



    




}
